﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Reflection;
using System.IO;
using System.Collections;

namespace IRC.NET
{
    internal class ParseUtils
    {
        private static Dictionary<int, string> _RegexTable = new Dictionary<int, string>();

        public static bool IsMatch(string input, string pattern)
        {
            return (Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase));
        }

        public static Dictionary<string, string> GetParameters(string input, string pattern)
        {
            if (!Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase))
            {
                throw new ArgumentException("Pattern didn't match input.");
            }

            // What we need to do first is grab all of the named groups from the pattern.
            string innerPattern = @"\(\?<(?<group>\S+)>";
            Match match = Regex.Match(input, pattern, RegexOptions.IgnoreCase);

            List<string> list = new List<string>();
            foreach(Group group in match.Groups) 
            {
                list.Add(group.Value);
            }

            return (null);
        }

        public static string GetPattern(int id)
        {
            if (ParseUtils._RegexTable.Count < 1)
            {
                ParseUtils._Inialize();
            }

            if (!ParseUtils._RegexTable.ContainsKey(id))
            {
                return (string.Empty);
            }

            return (ParseUtils._RegexTable[id]);
        }

        private static void _Inialize()
        {
            Assembly executing = Assembly.GetExecutingAssembly();
            System.IO.Stream stream = executing.GetManifestResourceStream("IRC.NET.regex table.txt");
            StreamReader reader = new StreamReader(stream);

            ParseUtils._RegexTable.Clear();

            while (!reader.EndOfStream)
            {
                string line = reader.ReadLine();

                if (string.IsNullOrEmpty(line))
                {
                    continue;
                }

                int idx = line.IndexOf(' '); // Get the first bit.
                string id = line.Substring(0, idx);
                line = line.Substring(idx + 1);
                ParseUtils._RegexTable.Add(int.Parse(id), line);
            }

            reader.Close();
            stream.Close();
        }
    }
}
